<?php

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Member\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Utility\Session\Session;
use Member\Model\MemberModel;
use Zend\View\Model\JsonModel;

class IndexController extends AbstractActionController {

    public function indexAction() {
        $Session = new Session();
        if ($Session->userid) {
            return $this->redirect()->toRoute('admin/child', array('controller' => 'Index', 'action' => 'index'));
        }
        return new ViewModel();
    }

    public function loginAction() {
        $Session = new Session();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $MemberModel = new MemberModel();
            $post = $request->getPost()->toArray();
            //检查用户名是否存在
            $Emails = $MemberModel->SelectByCond(array("username" => $post['email']))->toArray();
            if (!$Emails) {
                return new JsonModel(array("result" => false, 'type' => 'email', "msg" => '未找到当前E-mail,请重新输入!'));
            }
            //检查密码是否正确
            //检查用户名是否存在
            $Passwords = $MemberModel->SelectByCond(array("username" => $post['email'], 'password' => $post['password']))->toArray();
            if (!$Passwords) {
                return new JsonModel(array("result" => false, 'type' => 'password', "msg" => '您输入的密码有误,请重新输入'));
            }
            $Session->userid = $Passwords[0]['id'];
            $Session->username = $Passwords[0]['username'];
            $MemberModel->EditByCond(array("last_login_time" => date("Y-m-d H:i:s")), array("id" => $Passwords[0]['id']));
            $href = $this->url()->fromRoute('admin/child', array('controller' => 'index', 'action' => 'index'));
            return new JsonModel(array("result" => true, 'href' => $href));
        }
        return new JsonModel();
    }

    public function logoutAction() {
        $Session = new Session();
        $Session->clear();
        return $this->redirect()->toRoute('member/child', array('controller' => 'index', 'action' => 'index'));
    }

}
